package com.cy.dda.service.diligencing.impl;

import com.aliyun.oss.OSSClient;
import com.cy.dda.comm.exception.MsgException;
import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.dao.mapper.diligencing.*;
import com.cy.dda.dao.mapper.org.OrgMapper;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.ao.diligencing.DiligencingEditAO;
import com.cy.dda.model.ao.diligencing.DiligencingReportAuditAO;
import com.cy.dda.model.domain.diligencing.*;
import com.cy.dda.model.domain.org.Org;
import com.cy.dda.model.dto.comm.OSSFileDownloadDTO;
import com.cy.dda.model.dto.diligencing.DiligencingAdminListExportDTO;
import com.cy.dda.model.dto.diligencing.DiligencingImportDTO;
import com.cy.dda.model.enums.YesOrNo;
import com.cy.dda.model.enums.diligencing.DiligencingReportAuditResult;
import com.cy.dda.model.enums.diligencing.DiligencingStatus;
import com.cy.dda.model.query.diligencing.DiligencingAdminListQuery;
import com.cy.dda.model.query.diligencing.DiligencingListQuery;
import com.cy.dda.model.vo.diligencing.*;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.diligencing.DiligencingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 尽调 DiligencingService
 * @Author tanyilin
 * @Date 2019/5/29 17:44
 */
@Slf4j
@Service
public class DiligencingServiceImpl extends BaseService implements DiligencingService {

    @Autowired
    private OrgMapper                          orgMapper;
    @Autowired
    private DiligencingMapper                  diligencingMapper;
    @Autowired
    private DiligencingCustomerMapper          diligencingCustomerMapper;
    @Autowired
    private DiligencingReportMapper            diligencingReportMapper;
    @Autowired
    private DiligencingReportAuditRecordMapper diligencingReportAuditRecordMapper;
    @Autowired
    private DiligencingReportAttachmentMapper  diligencingReportAttachmentMapper;

    @Override
    public List<DiligencingImportDTO> getDiligencingImportDTO(MultipartFile multipartFile) {

        Workbook wb = null;
        try {
            if (CommonUtils.isExcel2003(multipartFile.getOriginalFilename())) {
                wb = new HSSFWorkbook(multipartFile.getInputStream());
            } else {
                wb = new XSSFWorkbook(multipartFile.getInputStream());
            }
        } catch (IOException e) {
            log.error("improtExcel error:", e);
            throw new MsgException("读取Excel文件异常");
        }
        //目标list
        List<DiligencingImportDTO> list = new ArrayList<>();

        Sheet sheet = wb.getSheetAt(0);
        log.info("表格长度==============》{}", sheet.getLastRowNum());

        for(int i = 1; i <= sheet.getLastRowNum(); i++) {
            log.info("第[{}]行数据", i);
            //得到 '行'
            Row row = sheet.getRow(i);

            Date entrustTime = row.getCell(1) == null ? null : row.getCell(1).getDateCellValue();
            String orgName = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
            state(!CommonUtils.isEmpty(orgName), "第" + i + "行数据的机构不可为空，请校验");
            String name = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
            state(!CommonUtils.isEmpty(name), "第" + i + "行数据的姓名不可为空，请校验");
            String idNo = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
            state(!CommonUtils.isEmpty(idNo), "第" + i + "行数据的身份证号码不可为空，请校验");
            String mobile = row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();
            state(!CommonUtils.isEmpty(mobile), "第" + i + "行数据的客户手机号码不可为空，请校验");

            String customerType = row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();
            String companyName = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();
            String homeAddress = row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue();
            String companyAddress = row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();
            String checkKeyPoints = row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue();
            String productName = row.getCell(11) == null ? "" : row.getCell(11).getStringCellValue();
            Date applyTime = row.getCell(12) == null ? null : row.getCell(12).getDateCellValue();
            String city = row.getCell(13) == null ? "" : row.getCell(13).getStringCellValue();

            DiligencingImportDTO dto = new DiligencingImportDTO();
            dto.setEntrustTime(entrustTime);
            dto.setOrgName(orgName);
            dto.setName(name);
            dto.setIdNo(idNo);
            dto.setMobile(mobile);
            dto.setCustomerType(customerType);
            dto.setCompanyName(companyName);
            dto.setHomeAddress(homeAddress);
            dto.setCompanyAddress(companyAddress);
            dto.setCheckKeyPoints(checkKeyPoints);
            dto.setProductName(productName);
            dto.setApplyTime(applyTime);
            dto.setCity(city);

            list.add(dto);
        }


        return list;
    }

    @Override
    @Transactional
    public void addDiligencings(List<DiligencingImportDTO> diligencingImportList) {

        Date time = new Date();
        //循环遍历
        for(int i = 0; i < diligencingImportList.size(); i++) {

            DiligencingImportDTO dto = diligencingImportList.get(i);

            //初始化索引ID
            Long orgId = 0L;
            Long diligencingCustomerId = 0L;

            //验证机构
            Org org = new Org();
            org.setName(dto.getOrgName());
            Org dbOrg = orgMapper.selectOne(org);
            if(dbOrg == null) {
                //如果机构不存在，则新增一个机构
                org.setCreateTime(time);
                org.setUpdateTime(time);
                orgMapper.insertSelective(org);
                //得到机构ID
                orgId = org.getId();
            }else {
                //机构已存在，得到机构ID
                orgId = dbOrg.getId();
            }

            //验证尽调客户
            DiligencingCustomer diligencingCustomer = new DiligencingCustomer();
            diligencingCustomer.setIdNo(dto.getIdNo());
            DiligencingCustomer dbDiligencingCustomer = diligencingCustomerMapper.selectOne(diligencingCustomer);
            if(dbDiligencingCustomer == null) {
                //如果客户不存在，则新增一个客户
                diligencingCustomer.setName(dto.getName());
                diligencingCustomer.setMobile(dto.getMobile());
                diligencingCustomer.setCreateTime(time);
                diligencingCustomer.setUpdateTime(time);
                diligencingCustomerMapper.insertSelective(diligencingCustomer);
                //得到尽调客户ID
                diligencingCustomerId = diligencingCustomer.getId();

            }else {
                //客户已存在，得到尽调客户ID
                diligencingCustomerId = dbDiligencingCustomer.getId();
            }

            //保存尽调案件数据
            Diligencing dbDiligencing = new Diligencing();
            dbDiligencing.setOrgId(orgId);
            dbDiligencing.setDiligencingCustomerId(diligencingCustomerId);
            dbDiligencing.setCustomerType(dto.getCustomerType());
            dbDiligencing.setProductName(dto.getProductName());
            dbDiligencing.setApplyTime(dto.getApplyTime());
            dbDiligencing = diligencingMapper.selectOne(dbDiligencing);
            if(dbDiligencing != null) {
                log.info("第" + (i + 1) + "条尽调案件数据疑是已入库，请勿重新导入");
                continue;
            }

            Diligencing newDiligencing = new Diligencing();
            BeanUtils.copyProperties(dto, newDiligencing);
            newDiligencing.setOrgId(orgId);
            newDiligencing.setDiligencingCustomerId(diligencingCustomerId);
            newDiligencing.setDiligencingStatus(DiligencingStatus.DISTRIBUTE_WAIT);
            newDiligencing.setCreateTime(time);
            newDiligencing.setUpdateTime(time);
            diligencingMapper.insertSelective(newDiligencing);

        }

    }

    @Override
    @Transactional
    public void appointDistributeDiligencing(Long diligencingId, Long userId) {

        Date time = new Date();

        Diligencing updateDiligencing = new Diligencing();
        updateDiligencing.setId(diligencingId);
        updateDiligencing.setUserId(userId);
        updateDiligencing.setDiligencingStatus(DiligencingStatus.PROCESSING);
        updateDiligencing.setDistributeTime(time);
        updateDiligencing.setUpdateTime(time);
        diligencingMapper.updateByPrimaryKeySelective(updateDiligencing);

    }

    @Override
    public PageBean<DiligencingAdminListVO> selectDiligencingAdminList(DiligencingAdminListQuery query) {

        int total = diligencingMapper.selectDiligencingAdminListCount(query);
        List<DiligencingAdminListVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = diligencingMapper.selectDiligencingAdminList(query);
            list.stream().forEach(d -> {
                d.setDiligencingStatusText(CommonUtils.isEmpty(d.getDiligencingStatus()) ? null : d.getDiligencingStatus().getText());
                d.setDiligencingResultText(CommonUtils.isEmpty(d.getDiligencingResult()) ? null : d.getDiligencingResult().getText());
            });
        }

        return new PageBean<>(list, total);
    }

    @Override
    public DiligencingAdminDetailVO getDiligencingAdminDetail(Long diligencingId) {

        //查询尽调案件数据详情
        DiligencingAdminDetailVO detailVO = diligencingMapper.selectDiligencingAdminDetail(diligencingId);
        state(detailVO != null, "数据异常，不存在该尽调案件！");

        //查询尽调报告详情
        DiligencingReport dbDiligencingReport = new DiligencingReport();
        dbDiligencingReport.setDiligencingId(diligencingId);
        dbDiligencingReport = diligencingReportMapper.selectOne(dbDiligencingReport);
        if(dbDiligencingReport != null) {
            //尽调报告已填写
            DiligencingReportAdminDetailVO reportDetailVO = new DiligencingReportAdminDetailVO();
            BeanUtils.copyProperties(dbDiligencingReport, reportDetailVO);
            reportDetailVO.setDiligencingReportId(dbDiligencingReport.getId());
            Long diligencingReportId = dbDiligencingReport.getId();

            //查询尽调报告审核记录
            List<DiligencingReportAuditRecordVO> reportAuditRecordList = diligencingReportAuditRecordMapper.selectDiligencingReportAuditRecord(diligencingReportId);

            //查询尽调报告-影音资料列表
            List<DiligencingReportAttachmentVO> reportAttachmentList = diligencingReportAttachmentMapper.selectDiligencingReportAttachment(diligencingReportId, null);

            detailVO.setReportDetail(reportDetailVO);
            detailVO.setReportAuditRecordList(reportAuditRecordList);
            detailVO.setReportAttachmentList(reportAttachmentList);
        }

        return detailVO;
    }

    @Override
    @Transactional
    public void doEditDiligencing(DiligencingEditAO editAO) {

        Date time = new Date();
        Long diligencingId = editAO.getDiligencingId();

        Diligencing dbDiligencing = diligencingMapper.selectByPrimaryKey(diligencingId);
        state(dbDiligencing != null, "数据异常，不存在该尽调案件！");

        //修改单位名称、地址、家庭地址
        Diligencing updateDiligencing = new Diligencing();
        BeanUtils.copyProperties(editAO, updateDiligencing);
        updateDiligencing.setId(diligencingId);
        updateDiligencing.setUpdateTime(time);
        diligencingMapper.updateByPrimaryKeySelective(updateDiligencing);

        //修改客户手机号码
        if(!CommonUtils.isEmpty(editAO.getMobile())) {
            DiligencingCustomer dbDiligencingCustomer = diligencingCustomerMapper.selectByPrimaryKey(dbDiligencing.getDiligencingCustomerId());
            if(!editAO.getMobile().equals(dbDiligencingCustomer.getMobile())) {
                //修改的号码与原号码不一样的时候
                DiligencingCustomer dbDiligencingCustomer2 = new DiligencingCustomer();
                dbDiligencingCustomer2.setMobile(editAO.getMobile());
                int count = diligencingCustomerMapper.selectCount(dbDiligencingCustomer2);
                state(count == 0, "该手机号码已存在！");
                //修改手机号码
                dbDiligencingCustomer.setMobile(editAO.getMobile());
                dbDiligencingCustomer.setUpdateTime(time);
                diligencingCustomerMapper.updateByPrimaryKeySelective(dbDiligencingCustomer);
            }
        }

    }

    @Override
    @Transactional
    public void doAuditDiligencingReport(DiligencingReportAuditAO auditAO, Long managerId) {

        Date time = new Date();
        Long diligencingReportId = auditAO.getDiligencingReportId();

        DiligencingReport dbDiligencingReport = diligencingReportMapper.selectByPrimaryKey(diligencingReportId);
        state(dbDiligencingReport != null, "数据异常，该尽调报告不存在");

        //新增一条审核记录
        DiligencingReportAuditRecord newDiligencingReportAuditRecord = new DiligencingReportAuditRecord();
        newDiligencingReportAuditRecord.setDiligencingReportId(diligencingReportId);
        newDiligencingReportAuditRecord.setResult(auditAO.getResult());
        newDiligencingReportAuditRecord.setRemark(auditAO.getRemark());
        newDiligencingReportAuditRecord.setManagerId(managerId);
        newDiligencingReportAuditRecord.setCreateTime(time);
        newDiligencingReportAuditRecord.setUpdateTime(time);
        diligencingReportAuditRecordMapper.insertSelective(newDiligencingReportAuditRecord);

        //更新尽调案件状态
        Diligencing updateDiligencing = new Diligencing();
        updateDiligencing.setId(dbDiligencingReport.getDiligencingId());
        if(DiligencingReportAuditResult.PASS.equals(auditAO.getResult())) {
            updateDiligencing.setDiligencingStatus(DiligencingStatus.COMPLETED);
        }else if(DiligencingReportAuditResult.RETURN.equals(auditAO.getResult())) {
            updateDiligencing.setDiligencingStatus(DiligencingStatus.REPORT_RETURN);
        }
        updateDiligencing.setUpdateTime(time);
        diligencingMapper.updateByPrimaryKeySelective(updateDiligencing);

    }

    @Override
    public List<DiligencingAdminListExportDTO> getDiligencingAdminListExport(DiligencingAdminListQuery query) {

        List<DiligencingAdminListExportDTO> list = diligencingMapper.selectDiligencingAdminListExport(query);

        state(!CommonUtils.isEmpty(list), "列表为空，不可导出");

        list.stream().forEach(d -> {
            d.setDiligencingResultText(CommonUtils.isEmpty(d.getDiligencingResult()) ? null : d.getDiligencingResult().getText());
            String diligencingSituation = "一、单位地址：";
            if(YesOrNo.YES.equals(d.getCompanyInfoIsReal())) {
                diligencingSituation = diligencingSituation.concat("真实；");
            }else if(YesOrNo.NO.equals(d.getCompanyInfoIsReal())) {
                diligencingSituation = diligencingSituation.concat("不真实（新单位名称：").concat(d.getRealCompanyName()).concat("；新地址：")
                        .concat(d.getRealCompanyAddress()).concat("）；");
            }
            diligencingSituation = diligencingSituation.concat("二、 单位地址跟公司招牌是否一致：");
            if(YesOrNo.YES.equals(d.getCompanyAddressWithSignboard())) {
                diligencingSituation = diligencingSituation.concat("一致；");
            }else if(YesOrNo.NO.equals(d.getCompanyAddressWithSignboard())) {
                diligencingSituation = diligencingSituation.concat("不一致；");
            }
            diligencingSituation = diligencingSituation.concat("三、 该单位是否正常经营：");
            if(YesOrNo.YES.equals(d.getCompanyNormalBusiness())) {
                diligencingSituation = diligencingSituation.concat("正常；");
            }else if(YesOrNo.NO.equals(d.getCompanyNormalBusiness())) {
                diligencingSituation = diligencingSituation.concat("不正常；");
            }
            if(!CommonUtils.isEmpty(d.getBusinessCondition())) {
                diligencingSituation = diligencingSituation.concat(d.getBusinessCondition()).concat("；");
            }
            if(!CommonUtils.isEmpty(d.getOperationCondition())) {
                diligencingSituation = diligencingSituation.concat("四、 公司从事该行业时间，运营情况：").concat(d.getOperationCondition()).concat("；");
            }
            if(!CommonUtils.isEmpty(d.getReasonsAndUsesOfLoans())) {
                diligencingSituation = diligencingSituation.concat("五、 客户为什么会贷这笔款？贷款用途：").concat(d.getReasonsAndUsesOfLoans()).concat("；");
            }
            if(!CommonUtils.isEmpty(d.getCustomerCurrentSituation())) {
                diligencingSituation = diligencingSituation.concat("六、 客户当前情况：").concat(d.getCustomerCurrentSituation()).concat("；");
            }

            d.setDiligencingSituation(diligencingSituation);
        });

        return list;
    }

    @Override
    public PageBean<DiligencingListVO> getDiligencingList(DiligencingListQuery query) {

        int total = diligencingMapper.selectDiligencingListCount(query);
        List<DiligencingListVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = diligencingMapper.selectDiligencingList(query);
            list.stream().forEach(d -> {
                d.setDiligencingStatusText(CommonUtils.isEmpty(d.getDiligencingStatus()) ? null : d.getDiligencingStatus().getText());
                d.setSex(CommonUtils.getSexByIdNo(d.getIdNo()));
                if(DiligencingStatus.COMPLETED.equals(d.getDiligencingStatus())) {
                    d.setSummary("尽调".concat(CommonUtils.isEmpty(d.getDiligencingResult()) ? "" : d.getDiligencingResult().getText())
                                        .concat("，")
                                        .concat(d.getDiligencingResultDesc()));
                }
            });
        }

        return new PageBean<>(list, total);
    }

    @Override
    public DiligencingDetailVO getDiligencingDetail(Long diligencingId) {

        DiligencingDetailVO detailVO = diligencingMapper.selectDiligencingDetail(diligencingId);
        state(detailVO != null, "数据异常，该尽调案件不存在！");
        detailVO.setMobile(CommonUtils.mobileFormat(detailVO.getMobile()));
        return detailVO;
    }

    @Override
    public List<OSSFileDownloadDTO> getOSSFileDownloadDTO(Long diligencingId) {

        //查询所有的文件
        //查询尽调报告详情
        DiligencingReport dbDiligencingReport = new DiligencingReport();
        dbDiligencingReport.setDiligencingId(diligencingId);
        dbDiligencingReport = diligencingReportMapper.selectOne(dbDiligencingReport);
        state(dbDiligencingReport != null, "数据异常！");

        DiligencingReportAttachment dbDiligencingReportAttachment = new DiligencingReportAttachment();
        dbDiligencingReportAttachment.setDiligencingReportId(dbDiligencingReport.getId());
        List<DiligencingReportAttachment> attachmentList = diligencingReportAttachmentMapper.select(dbDiligencingReportAttachment);

        //封装数组数据
        List<OSSFileDownloadDTO> list = new ArrayList<>();
        attachmentList.stream().forEach(a -> {
            OSSFileDownloadDTO bean = new OSSFileDownloadDTO();
            bean.setOssKey(a.getPath());
            bean.setFileName(a.getName());
            list.add(bean);
        });

        return list;
    }


}
